import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators, FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

import { UserService } from '../core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {
  form: FormGroup;
  name: AbstractControl;
  password: AbstractControl;
  remembered = true;
  submitted = false;
  authType: String = '';
  title: String = '';
  errors: string;
  constructor(
    fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private userService: UserService,
  ) {
    this.form = fb.group({
      name: [
        '',
        [Validators.required]
      ],
      password: [
        '',
        [Validators.required]
      ]
    });
    this.name = this.form.controls['name'];
    this.password = this.form.controls['password'];

    if (localStorage.getItem('name')) {
      this.name.setValue(localStorage.getItem('name'));
    }
  }
  public rememberAccount(): void {
    this.remembered = !this.remembered;

    if (this.remembered) {
      localStorage.setItem('name', this.name.value);
    } else {
      localStorage.removeItem('name');
    }
  }
  ngOnInit() {
    this.route.url.subscribe(data => {
      // Get the last piece of the URL (it's either 'login' or 'register')
      // console.log(data)
      // this.authType = data[data.length - 1].path;
      // console.log("xxx",this.authType)
      this.authType = "login";
      // Set a title for the page accordingly
      this.title = (this.authType === 'login') ? 'Sign in' : 'Sign up';
      // add form control for username if this is the register page
      if (this.authType === 'register') {
        this.form.addControl('name', new FormControl());
      }
    });
  }
  onSubmit(values: Object): void {
    this.submitted = true;
    this.errors = "";

    const credentials = this.form.value;
    // console.log("credentials:", credentials)
    this.userService
      .attemptAuth(this.authType, credentials)
      .subscribe(
        data => this.router.navigateByUrl('/'),
        err => {
          this.errors = err;
          this.submitted = false;
        }
      );
  }

  ngOnDestroy() {
  }
}
